package scatter.common.rest.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

import java.util.List;

/**
 * Created by yangwei
 * Created at 2020/12/10 20:20
 */
public class CommonWebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 密码加解密处理，用户添加的时候也会用到
     * @return
     */

    @Autowired(required = false)
    private List<CommonRestSecurityConfigure> commonRestSecurityConfigureList;

    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationManager authenticationManager = super.authenticationManager();

        if (commonRestSecurityConfigureList != null) {
            for (CommonRestSecurityConfigure commonRestSecurityConfigure : commonRestSecurityConfigureList) {
                commonRestSecurityConfigure.configure(http,authenticationManager);
            }
        }
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        if (commonRestSecurityConfigureList != null) {
            for (CommonRestSecurityConfigure commonRestSecurityConfigure : commonRestSecurityConfigureList) {
                commonRestSecurityConfigure.configure(auth,passwordEncoder());
            }
        }

    }

}
